package com.soup.lab.el;

import com.udojava.evalex.AbstractFunction;
import com.udojava.evalex.AbstractOperator;
import com.udojava.evalex.Expression;
import com.udojava.evalex.Function;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.List;

public class EvalExTestCase {

    @Test
    public void test() {
        // 普通表达式
        Assertions.assertEquals(13, new Expression("3 + 5 * 2").eval().intValue());;

        // 变量表达式
        Assertions.assertEquals(35, new Expression("(a+b)*c")
                .with("a", new BigDecimal(3))
                .and("b",  new BigDecimal(4))
                .and("c", new BigDecimal(5))
                .eval().intValue());

        Assertions.assertEquals("0.33", new Expression("1/3", new MathContext(2)).eval().toString());

        // 自定义函数
        Expression expression = new Expression("f(3)");
        expression.addFunction(new AbstractFunction("f", 1) {
            @Override
            public BigDecimal eval(List<BigDecimal> list) {
                return list.get(0) .multiply(list.get(0));
            }
        });
        Assertions.assertEquals(9, expression.eval().intValue());

        // 自定义运算符
        Expression optExp = new Expression("2$3");
        optExp.addOperator(new AbstractOperator("$", 10, true) {
            @Override
            public BigDecimal eval(BigDecimal a, BigDecimal b) {
                if(a.compareTo(b) > 0) {
                    return a.multiply(b);
                }
                return b.divide(a);
            }
        });
        Assertions.assertEquals(1.5, optExp.eval().floatValue());


    }


}
